package com.edu.policy.data.netty;

import com.edu.policy.common.service.RedisService;
import com.edu.policy.data.domain.ModbusData;
import com.zaxxer.hikari.HikariDataSource;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@Log4j2
@RequiredArgsConstructor
public class NettyServer {
    @Value("${db.port}")
    private String port;
    //TODO 减少线程到1，正常调到5-10
    private final NioEventLoopGroup bossGroup = new NioEventLoopGroup(10);
    private final NioEventLoopGroup workerGroup = new NioEventLoopGroup(10);
    private Channel serverChannel;
    /**
     * nettyServerHandler
     * 解析 Netty 接收到的 Modbus 数据。
     * 将数据存储到 TDengine 中。
     * 更新 Redis 中的最新数据。
     * */
    private final DataBuffer dataBuffer; // 数据缓存
    private final HikariDataSource tdengineDataSource;
    private final RedisService redisService;
    private final NettyServerHandler nettyServerHandler;

    @PostConstruct
    public void start() throws InterruptedException {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new ByteArrayDecoder());
                        ch.pipeline().addLast(new ByteArrayEncoder());
                        ch.pipeline().addLast(nettyServerHandler);
                    }
                });

        ChannelFuture f = b.bind(Integer.parseInt(port)).sync();
        serverChannel = f.channel();
        log.info("Netty server started on port: " + port);
        //TODO 启动定时任务,防止缓存数据积压
//        startFlushTask();
    }

    // 启动定时任务
    private void startFlushTask() {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(() -> {
            try {
                dataBuffer.flush(); // 刷新缓存
            } catch (Exception e) {
                log.error("定时刷新缓存失败", e);
            }
        }, 1, 1, TimeUnit.SECONDS); // 每隔 1 秒执行一次
    }

    @PreDestroy
    public void stop() throws InterruptedException {
        if (serverChannel != null) {
            serverChannel.close().sync();
        }
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        log.info("Netty server stopped.");
    }

}


